package com.mediacloud.app.newsmodule.service;

import java.lang.ref.WeakReference;

import com.mediacloud.app.cloud.ijkplayers.listener.PlayerListener;
import com.mediacloud.app.cloud.ijkplayersdk.music.MusicPlayer;
import com.mediacloud.app.cloud.ijkplayersdk.music.MusicPlayer.PlayCode;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.newsmodule.broadcast.AudioLiveBroadcast;
import com.mediacloud.app.newsmodule.service.servicenotification.MediaNotificationManager;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import org.greenrobot.eventbus.EventBus;

/**
 * 音频后台服务处理类
 * @author x
 *
 */
public class AudioLivePlayService extends AbsAudioPlayService implements AudioLiveBroadcast.AudioLiveBroad {
	public static final String TAG=AudioLivePlayService.class.getSimpleName();
	public MusicPlayer musicPlayer;
	protected ArticleItem currentLiveAudio;
	protected UpdateTimeHandler timeHandler;
	int delayUpdateTime=850;
	boolean isComplete=false;
	int playIndex=0;
	PlayCode VodPlayMode=PlayCode.ORDER_PLAY;
	long currentPosition=0;
	private AudioLiveBroadcast broadcast;

	public AudioLivePlayService()
	{
	}
	@Override
	public void onCreate()
	{
		super.onCreate();
		timeHandler=new UpdateTimeHandler(this);
		TelephonyManager tmgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		tmgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
		mMediaNotificationManager = new MediaNotificationManager(this,MediaNotificationManager.TYPE_LIVE);
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{
		//		flags=START_REDELIVER_INTENT;
		int action=intent!=null?intent.getIntExtra(AudioConst.Action, -1):-1;
		switch (action)
		{
			case AudioConst.PlayLive:
				playLiveStream(intent);
				timeHandler.mOwner=new WeakReference<>(this);
				showCurrentTime();
				break;
			case AudioConst.Pause:
				pauseStream(intent);
				break;
			case AudioConst.OnResume:
				onResumeStream(intent);
				showCurrentTime();
				break;
			case AudioConst.Stop:
				destory(intent);
				break;
			case AudioConst.StopUpdateTime:
				stopUpdateTime();
				break;
			case AudioConst.ChangeLine:
				isComplete=true;
				stopStream(intent);
				stopUpdateTime();
				break;
			case AudioConst.ChangePlayMode:
				int args=intent.getIntExtra(AudioConst.PlayMode, AudioConst.Normal);
				VodPlayMode=args==AudioConst.SingleLoop?PlayCode.SINGLE_LOOP_PLAY:PlayCode.ORDER_PLAY;
				if(musicPlayer!=null)
				{
					musicPlayer.setPlayCode(VodPlayMode);
				}
				break;
			case AudioConst.CREATE_ACTIVITY:
				unregisterBroad();
				break;
			case AudioConst.DESTROY_ACTIVITY:
				initBroad();
			default:
				break;
		}
		return flags;
	}

	protected void initBroad() {
		unregisterBroad();
		IntentFilter filter = new IntentFilter();
//		filter.addAction(AudioLiveBroadcast.Audio_UpdateTime);
//		filter.addAction(AudioLiveBroadcast.AudioComplete);
		filter.addAction(AudioLiveBroadcast.TOGGLE_AUDIO);
		broadcast = new AudioLiveBroadcast();
		broadcast.registed = true;
		registerReceiver(broadcast, filter);
		broadcast.audioLiveBroadHanlder = this;
	}

	protected void unregisterBroad(){
		if(broadcast != null && broadcast.registed){
			broadcast.registed = false;
			unregisterReceiver(broadcast);
			broadcast.audioLiveBroadHanlder = null;
			broadcast = null;
		}
	}

	protected void showCurrentTime()
	{
		timeHandler.sendEmptyMessageDelayed(AudioConst.UpdateTime, delayUpdateTime);
	}
	protected void playLiveStream(Intent intent)
	{
		String url=intent.getStringExtra("url");
		//		url="http://wow2.cnr.cn/live28/jjzs/playlist.m3u8";
		ArticleItem articleItem=intent.getParcelableExtra("data");
		CatalogItem catalogItem = intent.getParcelableExtra("catalog");
		mMediaNotificationManager.setCatalogItem(catalogItem);
		boolean isReplay=intent.getBooleanExtra(Intent.ACTION_ATTACH_DATA,false);
		if(articleItem==null)
			return;
		if(currentLiveAudio!=null)
		{
			if(currentLiveAudio.getId()==articleItem.getId())
			{
				if(!isPlay)
				{
					if(isComplete)
					{
						if(musicPlayer!=null)
						{
							musicPlayer.release();
						}
						//musicPlayer = null;
						initLivePlayer();
						musicPlayer.isLiveReplay=isReplay;
					}
					else
					{
						if(musicPlayer==null)
						{
							initLivePlayer();
						}
						musicPlayer.isLiveReplay=isReplay;
						musicPlayer.play();
						return;
					}
				}
				else
				{
					return;
				}
			}
		}
		currentLiveAudio=articleItem;
		if(isPlay&&!isComplete)
		{
			if(musicPlayer!=null)
			{
				musicPlayer.stop();
				musicPlayer.release();
			}
			musicPlayer=null;
		}
		if(musicPlayer==null)
		{
			initLivePlayer();
		}
		musicPlayer.isLiveReplay=isReplay;
		AudioItem audioItem=new AudioItem();
		audioItem.url=url;
		if(musicPlayer.getaddMediaObjs()!=null)
			musicPlayer.getaddMediaObjs().clear();
		musicPlayer.addMediaObjs(audioItem);
		musicPlayer.play();
		isPlay=true;
		startNotification(articleItem, true);
	}

	protected void initLivePlayer()
	{
		isComplete=false;
		musicPlayer=new MusicPlayer(this);
		musicPlayer.isLive=true;
		musicPlayer.setOnPlayerListener(new PlayerListener() {
			@Override
			public void onstop(int arg0) {
			}
			@Override
			public void onstartBuffer(int arg0) {
			}
			@Override
			public void onpause(int arg0) {
			}

			@Override
			public void oncomplete(int arg0) {
				isPlay=false;
				sendLiveEndBroad();
				clearLastPlayAudioInfo();
			}

			@Override
			public void onSeekComplete(int arg0) {
			}

			@Override
			public void onSeek(int arg0, long arg1, long arg2) {
				//showCurrentTime();
			}

			@Override
			public void onPrepared(int arg0) {
				isComplete=false;
			}

			@Override
			public void onPlayingBufferCache(int arg0, int arg1) {

			}

			@Override
			public void onError(int arg0, int arg1, int arg2) {
				isPlay=false;
				sendLiveEndBroad();
				clearLastPlayAudioInfo();
			}

			@Override
			public void onEndBuffer(int arg0) {

			}
		});
	}


	protected void sendLiveEndBroad()
	{
		isComplete=true;
		if(musicPlayer==null)
			return;
		Intent intent=new Intent();
		intent.setAction(AudioLiveBroadcast.AudioComplete);
		if(currentLiveAudio!=null)
			intent.putExtra(Intent.EXTRA_LOCUS_ID,currentLiveAudio.getId());
		intent.putExtra(Intent.EXTRA_PACKAGE_NAME,getPackageName());
		sendBroadcast(intent);
		musicPlayer.stop();
		stopForeground(true);
	}

	protected void pauseStream(Intent intent)
	{
		if(musicPlayer!=null)
			musicPlayer.pause();
		isPlay=false;
		timeHandler.removeMessages(AudioConst.UpdateTime);
		startNotification(currentLiveAudio, false);
	}

	protected void onResumeStream(Intent intent)
	{
		if(musicPlayer!=null)
		{
			if(isComplete==false)
			{
				musicPlayer.start();
				showCurrentTime();
			}
			else
			{

			}
		}
		isPlay=true;
		startNotification(currentLiveAudio, true);
	}

	protected void stopStream(Intent intent)
	{
		if(musicPlayer!=null)
		{
			if(!isComplete)
			{
				musicPlayer.stop();
			}
			musicPlayer.release();
			musicPlayer=null;
		}
		isPlay=false;
		if(currentLiveAudio != null){
			startNotification(currentLiveAudio, false);
		}
	}
	@Override
	protected void stopUpdateTime()
	{
		if(timeHandler!=null)
		{
			timeHandler.removeMessages(AudioConst.UpdateTime);
		}
	}

	protected void destory(Intent intent)
	{
		isComplete=true;
		stopStream(intent);
		stopUpdateTime();
		if(timeHandler.mOwner!=null){
			timeHandler.mOwner.clear();
		}
		stopForeground(true);
		stopSelf();
		currentLiveAudio=null;
	}

	@Override
	public void onDestroy()
	{
		mMediaNotificationManager.onDestroy();
		TelephonyManager tmgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		tmgr.listen(phoneStateListener, 0);
		unregisterBroad();
		clearLastPlayAudioInfo();
		super.onDestroy();
	}

	@Override
	public void updateCurrentTime(Intent intent) {

	}

	@Override
	public void audioComplete(Intent intent) {

	}

	@Override
	public void togglePauseAudio(Intent intent) {
		if (isPlay){
			pauseStream(null);
		}else {
			onResumeStream(null);
		}
	}

	class UpdateTimeHandler extends WeakHandler<AudioLivePlayService>
	{

		public UpdateTimeHandler(AudioLivePlayService owner)
		{
			super(owner);
		}
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			switch(msg.what)
			{
				case AudioConst.UpdateTime:
					AudioLivePlayService audioLivePlayService=getOwner();
					if(audioLivePlayService==null||audioLivePlayService.musicPlayer==null||audioLivePlayService.isComplete)
						return;
					currentPosition=audioLivePlayService.musicPlayer.getcurrentPlayPosition();
					showCurrentTime();
					Intent intent=new Intent();
					intent.setAction(AudioLiveBroadcast.Audio_UpdateTime);
					intent.putExtra(Intent.EXTRA_PACKAGE_NAME,getPackageName());
					if(audioLivePlayService.currentLiveAudio!=null)
						intent.putExtra(Intent.EXTRA_LOCUS_ID,audioLivePlayService.currentLiveAudio.getId());
					intent.putExtra("time", audioLivePlayService.musicPlayer.getcurrentPlayPosition());
					sendBroadcast(intent);
					break;
			}
		}

	}
	protected static abstract class WeakHandler<T> extends Handler
	{
		WeakReference<T> mOwner;

		public WeakHandler(T owner) {
			mOwner = new WeakReference<T>(owner);
		}

		public T getOwner()
		{
			return mOwner.get();
		}
	}


	private PhoneStateListener phoneStateListener=new PhoneStateListener()
	{
		boolean beforePauseIsPlay=false;
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			super.onCallStateChanged(state, incomingNumber);

			if (state == TelephonyManager.CALL_STATE_RINGING)
			{
				beforePauseIsPlay=isPlay;
				if(isPlay)
				{
					pauseStream(null);
					EventBus.getDefault().post(new Boolean(false));
				}
			} else if (state == TelephonyManager.CALL_STATE_OFFHOOK)
			{
				beforePauseIsPlay=isPlay;
				if(isPlay)
				{
					pauseStream(null);
					EventBus.getDefault().post(new Boolean(false));
				}

			}
			else if (state == TelephonyManager.CALL_STATE_IDLE)
			{
				if(beforePauseIsPlay)
				{
					onResumeStream(null);
					showCurrentTime();
					EventBus.getDefault().post(new Boolean(true));
				}
			}
		}
	};
}